chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
    if (request.action === "capture-visible") {
        chrome.tabs.captureVisibleTab(null, {format: 'png'}, function (dataUrl) {
            chrome.downloads.download({
                url: dataUrl, filename: 'screenshot.png'
            });
        });
    }
});

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
    if (request.action === "capture-entire") {
        captureScrollingScreenshot(function (dataUrl) {
            console.log(dataUrl);
            chrome.downloads.download({
                url: dataUrl, filename: 'screenshot.png'
            });
        });
    }
});


function captureScrollingScreenshot(callback) {
    var element = document.documentElement;
    var scrollHeight = element.scrollHeight;
    var clientHeight = element.clientHeight;
    var maxHeight = Math.max(scrollHeight, clientHeight);
    var canvas = document.createElement('canvas');
    canvas.width = element.clientWidth;
    canvas.height = maxHeight;
    var context = canvas.getContext('2d');
    var offsetY = 0;

    function captureScreen() {
        html2canvas(element, {
            scrollY: offsetY,
            windowWidth: element.clientWidth,
            windowHeight: Math.min(clientHeight, maxHeight - offsetY),
            canvas: canvas,
            logging: true,
            onclone: function (doc) {
                return doc;
            },
            onrendered: function (canvas) {
                context.drawImage(canvas, 0, offsetY);
                offsetY += canvas.height;
                if (offsetY < maxHeight) {
                    captureScreen();
                } else {
                    var dataUrl = canvas.toDataURL();
                    callback(dataUrl);
                }
            },
        });
    }

    captureScreen();
}


